/**
 * 
 */
package com.edocbase.desktopserver.impl.jetty;

import java.io.File;
import java.util.Map;

import org.mortbay.jetty.Server;
import org.mortbay.jetty.nio.SelectChannelConnector;
import org.mortbay.jetty.servlet.ServletHolder;
import org.mortbay.jetty.webapp.WebAppContext;
import org.mortbay.thread.QueuedThreadPool;

import com.edocbase.desktopserver.IDesktopServer;

import freemarker.ext.servlet.FreemarkerServlet;

public class JettyDesktopServer implements IDesktopServer{
	public static String WEB_HOME_URL = "";
	private Map<String, String> parameters = null;
	private Server server;
	private File webHome = null;
	private File templateHome;
	private int port=8889;
	public JettyDesktopServer() {
		super();
		//this.webHome = webHome;
	}

	public void start() throws Exception {
		System.setProperty("org.mortbay.util.URI.charset", "GB2312");
		String dir = webHome.getAbsolutePath();
		String webappPath = dir;
		server = new Server();

		QueuedThreadPool threadPool = new QueuedThreadPool();
		threadPool.setName("desktop server");
		threadPool.setMinThreads(2);
		threadPool.setMaxThreads(5);
		threadPool.setMaxIdleTimeMs(1000);
		// threadPool.start();
		server.setThreadPool(threadPool);

		SelectChannelConnector connector = new SelectChannelConnector();
		connector.setPort(port);
		server.addConnector(connector);

		WebAppContext webApp = new WebAppContext();
		webApp.setContextPath("/");
		webApp.setResourceBase(webappPath);
		FreemarkerServlet freemarker = new FreemarkerServlet();
		//ServletConfig cfg = new ServletConfiguration(freemarker);
		//FilterHolder filterHolder = new FilterHolder(new ActionFilter());
		webApp.addFilter(ActionFilter.class,"*.do",1);
		
		//webApp.setHandler(new ActionHandler());
		ServletHolder freemarkerHolder = new ServletHolder(freemarker);
		freemarkerHolder.setInitParameter("TemplatePath", "templates");
		webApp.addServlet(freemarkerHolder, "*.ftl");
		
		WEB_HOME_URL = "http://localhost:"+port+"/";
		server.setHandler(webApp);
		server.setStopAtShutdown(true);

		server.start();
	}

	public void shutdown(){
		server.destroy();
	}

	@Override
	public void initParameter(Map<String, String> parameters) {
		this.parameters = parameters;
		String webhome = parameters.get(WEB_HOME_KEY);
		webHome = new File(webhome);
		templateHome = new File(webHome,"templates");
		if (parameters.containsKey(SERVER_PORT_KEY)){
			String portStr = parameters.get(SERVER_PORT_KEY);
			port = Integer.parseInt(portStr);
		}
	}

	@Override
	public void stop() {
		try {
			server.stop();
		} catch (Exception e) {
			e.printStackTrace(System.err);
		}
		server.destroy();
	}

}
